package parser

import (
	"gc-rds-ha/internal/common"
	"gc-rds-ha/internal/dao"
	"gc-rds-ha/internal/dao/mysql_sync"
	msg "gc-rds-ha/scripts"
	"strings"

	log "github.com/sirupsen/logrus"

	"gorm.io/gorm"
)

func GetAddTopology(topologyInfos []mysql_sync.TopologyInfo, ClusterInfo mysql_sync.ClusterInfo) error {
	clusterAlias := ClusterInfo.ClusterName
	if ClusterInfo.ClusterAlias != "" {
		clusterAlias = ClusterInfo.ClusterAlias
	}
	var datas []*mysql_sync.MySQLClusterTopology
	if len(topologyInfos) <= 0 {
		return nil
	}
	if err := dao.DB.Transaction(func(tx *gorm.DB) error {
		if err := addHistory(clusterAlias, tx); err != nil {
			log.WithFields(log.Fields{
				"ClusterAlias": clusterAlias,
			}).Info("sync addHistory error ")
		}
		for _, topologyInfo := range topologyInfos {
			role := common.SlaveName
			if topologyInfo.MasterKey.Hostname == "" {
				role = common.MasterName
			}
			valid := msg.EIsLastCheckValid_Valid
			if !topologyInfo.IsLastCheckValid {
				valid = msg.EIsLastCheckValid_Invalid
			}
			data := &mysql_sync.MySQLClusterTopology{
				Host:             topologyInfo.Key.Hostname,
				Port:             topologyInfo.Key.Port,
				Role:             role,
				InstanceAlias:    topologyInfo.InstanceAlias,
				ClusterAlias:     clusterAlias,
				IsLastCheckValid: valid,
				MgrIsEnable:      topologyInfo.ReplicationGroupIsSinglePrimary,
				MgrRole:          topologyInfo.ReplicationGroupMemberRole,
				MgrState:         topologyInfo.ReplicationIOThreadState,
				Problems:         strings.Join(topologyInfo.Problems, ","),
			}
			datas = append(datas, data)
		}

		if err := mysql_sync.BatchCreateForSql(datas, tx); err != nil {
			return err
		}
		return nil
	}); err != nil {
		return err
	}

	return nil
}

func addHistory(ClusterAlias string, tx *gorm.DB) error {
	var (
		clusterTopologyModel = &mysql_sync.MySQLClusterTopology{
			ClusterAlias: ClusterAlias,
		}
		topologyHistoryData = make([]*mysql_sync.MySQLClusterTopologyHistory, 0)
		err                 error
	)

	topologyList, err := clusterTopologyModel.List(common.Offset, common.Limit)
	if err != nil {
		return err
	}

	for _, t := range topologyList {
		topologyHistoryData = append(topologyHistoryData, &mysql_sync.MySQLClusterTopologyHistory{
			Role:         t.Role,
			Host:         t.Host,
			Port:         t.Port,
			ClusterAlias: t.ClusterAlias,
			MgrRole:      t.MgrRole,
			MgrIsEnable:  t.MgrIsEnable,
			SyncNum:      t.SyncNum,
		})
	}
	if len(topologyList) > 0 {
		if err = mysql_sync.BatchCreateHistoryForSql(topologyHistoryData, tx); err != nil {
			return err
		}
	}
	return nil
}
